引用構造方法

目的是為了「創建對象」

格式:
	類名::new
	範例:
		Student::new
//匿名內部類寫法
ArrayList<String> list = new ArrayList<>();  
Collections.addAll(list, "John,15", "Alice,20", "Michael,17", "Emma,21",  
        "David,19","Mitchell,22");  
List<Student> collect = list.stream().map(new Function<String, Student>() {  
  
    @Override  
    public Student apply(String s) {  
        String[] arr = s.split(",");  
        String name = arr[0];  
        int age = Integer.parseInt(arr[1]);  
        return new Student(name, age);  
    }}).collect(Collectors.toList());  
  
System.out.println(collect);
//引用方法寫法
List<Student> collect = list.streamnew).collect(Collectors.toList();  
System.out.println(collect);
方法引用的規則

因為方法引用的規定 "引用方法的形參與返回值必須與抽象方法保持一致",所以通常你會需要再特別寫一個constructor來滿足規則

private String name;  
  
private int age;  
  
public Student() {  
}  
  
public Student(String str){  
	//因為抽象方法是傳入一個str 所以我們要拿到str後再做處理
    String[] arr = str.split(",");  
    this.name = arr[0];  
    this.age = Integer.parseInt(arr[1]);  
	//構造方法會回傳一個自己類的對象,所以返回值會一致
}  
  
public Student(String name, int age) {  
    this.name = name;  
    this.age = age;  
}

順便看看toList的底層
image.png
也是使用引用方法來完成的